package com.menghao.rpc.consumer.discovery.tcp;

import com.menghao.rpc.consumer.discovery.ProviderDiscovery;
import com.menghao.rpc.consumer.discovery.ReferenceRepository;
import com.menghao.rpc.consumer.handle.JdkProxyFactory;
import com.menghao.rpc.consumer.handle.tcp.TcpReferenceAgent;
import com.menghao.rpc.consumer.handle.ReferenceAgent;
import com.menghao.rpc.consumer.model.ReferenceKey;
import com.menghao.rpc.netty.TcpConnectionContainer;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>Tcp方式代理对象仓库.</br>
 * <p>存放 ReferenceKey-TcpReferenceAgent 对应关系</p>
 * <p>作为TcpReferenceAgent的一级缓存，避免重复从ZooKeeper获取节点信息</p>
 *
 * @author MarvelCode
 */
public class TcpReferenceRepository implements ReferenceRepository {

    private JdkProxyFactory proxyFactory;

    private ProviderDiscovery providerDiscovery;

    private Map<ReferenceKey, ReferenceAgent> referenceCache = new HashMap<>();

    public TcpReferenceRepository(JdkProxyFactory proxyFactory, ProviderDiscovery providerDiscovery) {
        this.proxyFactory = proxyFactory;
        this.providerDiscovery = providerDiscovery;
    }

    @Override
    public Object getReference(ReferenceKey referenceKey) {
        if (referenceCache.get(referenceKey) != null) {
            return proxyFactory.getProxy(referenceCache.get(referenceKey));
        }
        ReferenceAgent referenceAgent = new TcpReferenceAgent(referenceKey);
        // Tcp方式 @Reference 代理初始化
        providerDiscovery.initReferenceAgent(referenceAgent);
        referenceCache.putIfAbsent(referenceKey, referenceAgent);
        return proxyFactory.getProxy(referenceAgent);
    }
}
